import React, { useEffect, useState, useRef } from "react";
import { Canvas } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
import * as THREE from "three";
import { Button, Select } from "antd";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { useTranslation } from 'react-i18next'
import "./AiHome.css";

const ThreeScene: React.FC = () => {
  const {t}=useTranslation()
  const [modelUrl] = useState("/modules/4合一.glb");
  const [index, setIndex] = useState(0);
  const [selectedAction, setSelectedAction] = useState<THREE.AnimationClip[]>(
    []
  );
  const dragbox = useRef<HTMLDivElement | null>(null);
  
  
  useEffect(() => {
    // 拖拽逻辑保持不变
    const handleMouseDown = (e: MouseEvent) => {
      if (!dragbox.current) return;
      console.log('1',e.pageX)
      console.log('2',dragbox.current.offsetLeft)
      const x = e.pageX - dragbox.current.offsetLeft; // 计算鼠标点击位置相对于拖拽框左上角的x坐标
      const y = e.pageY - dragbox.current.offsetTop; // 计算鼠标点击位置相对于拖拽框左上角的y坐标
      // 添加鼠标移动的事件监听
      const handleMouseMove = (e: MouseEvent) => {
        if (!dragbox.current) return;
        dragbox.current.style.left = `${e.pageX - x}px`;
        dragbox.current.style.top = `${e.pageY - y}px`;
      };
       // 添加鼠标松开的事件监听
      const handleMouseUp = () => {
        document.removeEventListener("mousemove", handleMouseMove);
        document.removeEventListener("mouseup", handleMouseUp);
      };
       // 添加鼠标移动和鼠标松开的事件监听
      document.addEventListener("mousemove", handleMouseMove);
      document.addEventListener("mouseup", handleMouseUp);
    };

    if (dragbox.current) {
      dragbox.current.addEventListener("mousedown", handleMouseDown);
    }

    return () => {
      if (dragbox.current) {
        dragbox.current.removeEventListener("mousedown", handleMouseDown);
      }
    };
  }, [dragbox]);

  // 切换动作的逻辑保持不变
  const handleChange = (value: string) => {
    if (value === "你没时间了") {
      setIndex(0);
    } else if (value === "转圈圈") {
      setIndex(1);
    } else if (value === "给我爬") {
      setIndex(3);
    } else if (value === "小跳一下") {
      setIndex(2);
    }
  
  };
  
  //根据语音内容切换动作
  useEffect(()=>{
    // 监听来自 BottomCom 的语音动作切换事件
    const handleVoiceAction=(even:CustomEvent<string>)=>{
        handleChange(even.detail) // 直接调用 handleChange 切换动作
    }
     // 添加自定义事件监听
    window.addEventListener("voice-action",handleVoiceAction as EventListener)

    return ()=>{
      window.removeEventListener("voice-action",handleVoiceAction as EventListener)
    }
  },[])
 

  // 模型加载和动画逻辑保持不变
  const [model, setModel] = useState<THREE.Group | null>(null); // 用于存储加载的模型
  const [isAnimationPaused] = useState(false); // 用于控制动画是否暂停
  let animationFrameId: number | null = null; // 用于存储动画帧ID
  let currentAction: THREE.AnimationAction | null = null; // 用于存储当前播放的动画动作
  
  useEffect(() => {
    const mixer: any = new THREE.AnimationMixer(null); // 用于存储动画混合器
    const loader = new GLTFLoader(); // 创建GLTFLoader实例
     // 加载模型
    loader.load(
      modelUrl,
      (gltf) => {
        const loadedModel = gltf.scene; // 获取加载的模型
        setSelectedAction(gltf.animations); // 获取模型的所有动画剪辑

        const scale = 2.5; // 根据模型大小调整缩放比例
        loadedModel.scale.set(scale, scale, scale); // 根据模型大小调整缩放比例
        loadedModel.position.set(0, -2, 0); // 根据模型大小调整位置

        setModel(loadedModel); 
          // 播放动画
        if (mixer.current) {
          mixer.current.stopAllAction(); // 停止所有动画
          if (animationFrameId) {
            cancelAnimationFrame(animationFrameId); // 取消之前的动画帧
          }
          currentAction = null; // 重置当前动作
        }

        mixer.current = new THREE.AnimationMixer(loadedModel); // 创建新的动画混合器
        const clip = gltf.animations[index]; // 获取当前索引对应的动画剪辑
      
        function isMesh(object: THREE.Object3D): object is THREE.Mesh {
          return object instanceof THREE.Mesh; // 判断对象是否为网格对象
        }
       
        loadedModel.traverse((child) => { // 遍历模型的所有子对象
          if (child && isMesh(child) && mixer.current) { // 如果子对象是网格对象且动画混合器存在
            const action = mixer.current.clipAction(clip); // 获取动画动作
            action.timeScale = 0.4; // 调整动画播放速度
            action.clampWhenFinished = false; // 设置动画在完成时是否停止
            action.play(); // 播放动画
            currentAction = action; // 更新当前动作
          }
        });
          // 创建动画循环
        const animate = () => { 
          requestAnimationFrame(animate); // 请求下一帧动画
          if (mixer.current && !isAnimationPaused && currentAction) { // 如果动画混合器存在且动画未暂停且当前动作存在
            mixer.current.update(0.01); // 更新动画混合器
          }
        };

        animationFrameId = requestAnimationFrame(animate); // 开始动画循环
      },
      undefined,
      (error) => {
        console.error("Error loading model:", error);
      }
    );

    return () => {
      if (mixer.current) { // 如果动画混合器存在
        mixer.current.stopAllAction(); // 停止所有动画
        if (animationFrameId) { // 如果动画帧ID存在
          cancelAnimationFrame(animationFrameId); // 取消动画帧
        }
      }
    };
  }, [modelUrl, index]);

  return (
    <div className="canvas-container">
      <Canvas>
        <ambientLight intensity={3} />      {/* 环境光 */}
        <directionalLight position={[10, 10, 10]} intensity={3} />  {/* 平行光 */}
        {model && (
          <>
            <primitive object={model} />  {/* 渲染模型 */}
          
          </>
        )} 
        <OrbitControls /> {/* 视角控制器 */}
      </Canvas>

      <div className="button-container" ref={dragbox}>
        <Select
          defaultValue="切换动作"
          activeBorderColor='#1677ff'
          activeOutlineColor="rgba(5,145,255,0.1)"
          style={{ width: 120,background:'#1677ff' }}
          onChange={handleChange}
          options={[
            { value: "你没时间了" },
            { value: "转圈圈" },
            { value: "给我爬" },
            { value: "小跳一下" },
          ]}
        />
        
      </div>
    </div>
  );
};

export default ThreeScene;
